package com.iot.aliyun.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.iot.aliyun.handler.ResultHandler;
import com.iot.commonutils.utils.Result;
import org.springframework.stereotype.Component;


@Component
public class ThingModelUtil {

    //公共参数

    String regionId="cn-shanghai";//注册地ID

    String accessKeyId="LTAI4G1NEHgpt3QYNyjUyVaE";

    String secret="8Z9VP1S7KfeWDWdF6gm9Djnuy03w0m";

    String iotInstanceId;//企业实例ID

    String sysDomain="iot."+regionId+".aliyuncs.com";//系统域名

    String sysVersion="2018-01-20";//系统版本


    /**
     * 调用该接口为指定产品的物模型新增功能，支持同时新增物模型拓展描述
     * @param ProductKey 产品的唯一标识
     * @param ThingModelJson 新增的功能定义详情
     * @param FunctionBlockId 物模型自定义模块标识符，在产品中具有唯一性
     * @param FunctionBlockName 物模型的自定义模块名称
     * @return
     */
    public Result CreateThingModel(String ProductKey,String ThingModelJson,String FunctionBlockId,String FunctionBlockName){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("CreateThingModel");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("ThingModelJson",ThingModelJson);
        request.putQueryParameter("FunctionBlockId",FunctionBlockId);
        request.putQueryParameter("FunctionBlockName",FunctionBlockName);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口更新指定产品物模型中的单个功能，支持同步更新物模型的拓展描述
     * @param ProductKey 要更新的物模型的产品唯一标识
     * @param Identifier 功能的标识符
     * @param ThingModelJson 新的功能定义详情
     * @param FunctionBlockId 物模型自定义模块标识符
     * @param FunctionBlockName 物模型的自定义名称模块
     * @return
     */
    public Result UpdateThingModel(String ProductKey,String Identifier,String ThingModelJson,String FunctionBlockId,String FunctionBlockName){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("UpdateThingModel");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("Identifier",Identifier);
        request.putQueryParameter("ThingModelJson",ThingModelJson);
        request.putQueryParameter("FunctionBlockId",FunctionBlockId);
        request.putQueryParameter("FunctionBlockName",FunctionBlockName);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口查看指定产品物模型中的功能定义详情
     * @param ProductKey 要查询的产品唯一标识
     * @param ResourceGroupId 资源组id（目前不传入此参数）
     * @param ModelVersion 要查看的物模型版本号
     * @param FunctionBlockId 物模型自定义模块标识符（不传入此参数时，查询默认模块数据）
     * @return
     */
    public Result QueryThingModel(String ProductKey,String ResourceGroupId,String ModelVersion,String FunctionBlockId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("QueryThingModel");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("ResourceGroupId",ResourceGroupId);
        request.putQueryParameter("ModelVersion",ModelVersion);
        request.putQueryParameter("FunctionBlockId",FunctionBlockId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口发布指定产品的物模型
     * @param ProductKey 产品的唯一标识
     * @param ResourceGroupId 资源组id
     * @param ModelVersion 设置物模型的版本号
     * @param Description 物模型版本的描述
     * @return
     */
    public Result PublishThingModel(String ProductKey,String ResourceGroupId,String ModelVersion,String Description){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("PublishThingModel");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("ResourceGroupId",ResourceGroupId);
        request.putQueryParameter("ModelVersion",ModelVersion);
        request.putQueryParameter("Description",Description);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口查询指定产品的已发布物模型TSL
     * @param ProductKey 要查询的产品的唯一标识
     * @param ResourceGroupId 资源组id
     * @param Simple 是否获取精简版物模型信息，若不传入此参数，则默认为false：获取完整的物模型信息
     * @param ModelVersion 物模型版本号，为空时返回已发布的最新版本
     * @param FunctionBlockId 物模型自定义模块标识符，不传入此参数时，查询默认模块数据
     * @return
     */
    public Result GetThingModelTslPublished(String ProductKey,String ResourceGroupId,Boolean Simple,String ModelVersion,String FunctionBlockId){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("GetThingModelTslPublished");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("ResourceGroupId",ResourceGroupId);
        request.putQueryParameter("Simple",Simple.toString());
        request.putQueryParameter("ModelVersion",ModelVersion);
        request.putQueryParameter("FunctionBlockId",FunctionBlockId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口获取物联网平台预定义的标准产品品类列表
     * @return
     */
    public Result ListThingTemplates(){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("ListThingTemplates");
        request.putQueryParameter("RegionId",regionId);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }


    //物模型使用相关API
    /**
     * 调用该接口为指定设备设置属性值
     * @param Items 要设置的属性信息，数据格式为JSON String。属性组成为 属性标识符Key：属性值Value，多个属性用英文逗号隔开
     * @param IotId 设备唯一标识，如果传入此参数则无需传入ProductKey和DeviceName，如果您同时传入IotId和ProductKey与DeviceName组合，则以IotId为准。
     * @param DeviceName 设备名称，如果传入此参数，需同时传入ProductKey
     * @param ProductKey 设备所隶属的产品的唯一标识，如果传入此参数，需同时传入DeviceName
     * @return 因为云端下发属性设置命令和设备接收并执行该命令是异步的，所以调用该接口时，返回的成功结果只表示云端下发属性设置的请求成功，不能保证设备端收到并执行了该请求。需设备端SDK成功响应云端设置设备属性值的请求，设备属性值才能真正设置成功。
     */
    public Result SetDeviceProperty(String Items,String IotId,String DeviceName,String ProductKey){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("SetDeviceProperty");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("Items",Items);
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("IotId",IotId);
        request.putQueryParameter("DeviceName",DeviceName);
        request.putQueryParameter("ProductKey",ProductKey);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口查询指定设备的属性记录（仅能查询最近30天内的属性数据）
     * @param Asc 返回结果中属性记录的排序方式。0：倒序，1：正序
     * @param EndTime 要查询的属性记录的结束时间。取值为毫秒值时间戳
     * @param Identifier 要查询的属性标识符，若设备有多个属性，可多次重复调用该接口查询。（如果是自定义（非默认）模块testFb下属性temperature，则参数值为testFb:temperature）
     * @param PageSize 返回结果中每页的记录数。数量限制：每页最多可显示50条
     * @param StartTime 要查询的属性记录的开始时间，取值为毫秒时间戳
     * @param IotId 要查询的设备唯一标识，如果传入该参数，则无需传入ProductKey和DeviceName，如果同时传入IotId和ProductKey与DeviceName组合，则以IotId为准。
     * @param ProductKey 要查询设备所隶属的产品唯一标识，如果传入该参数，需同时传入DeviceName
     * @param DeviceName 要查询的设备名称，如果传入该参数，需同时传入ProductKey
     * @return
     */
    public Result QueryDevicePropertyData(Integer Asc,Long EndTime,String Identifier,Integer PageSize,Long StartTime,String IotId,String ProductKey,String DeviceName){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("QueryDevicePropertyData");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("Asc",Asc.toString());
        request.putQueryParameter("EndTime",EndTime.toString());
        request.putQueryParameter("Identifier",Identifier);
        request.putQueryParameter("PageSize",PageSize.toString());
        request.putQueryParameter("StartTime",StartTime.toString());
        request.putQueryParameter("IotInstanceId",iotInstanceId);
        request.putQueryParameter("IotId",IotId);
        request.putQueryParameter("ProductKey",ProductKey);
        request.putQueryParameter("DeviceName",DeviceName);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }
}
